var qiniu = require('qiniu-js')
// qiniuToken 需要从后台请求
let qiniuToken: string = ""

import { getQiniuToken } from '@/api/visionapi/index'


/**
 * 目标是去掉文件路径中的后缀
 * @param str 一个文件路径参数，可以带后缀 abc.mp4
 * @param suffix 后缀，例如： .mp4
 * @returns 返回一个不带后缀的文件名称
 */
export function removeSuffix(str: string, suffix: string) {
    if (str.endsWith(suffix)) {
        return str.slice(0, -suffix.length);
    }
    return str;
}



export function getuuid(len: any, radix: any) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
    var uuid = []
    var i = 0
    radix = radix || chars.length

    if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
    } else {
        var r
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
        uuid[14] = '4'

        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random() * 16
                uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
            }
        }
    }

    return uuid.join('')
}

export function getTimeId(len: Number = 8, radix: Number = 12) {
    const time = new Date().getTime()
    const uuid = getuuid(len, radix)
    return `${time}${uuid}`
}
export function createPic() {
    var now = new Date();
    var year = now.getFullYear(); //得到年份
    var month = now.getMonth();//得到月份
    var date = now.getDate();//得到日期
    month = month + 1;
    if (month < 10) month = 0 + month;
    if (date < 10) date = 0 + date;
    var number = now.getSeconds() % 43; //这将产生一个基于目前时间的0到42的整数。
    var time = year + '/' + month + '/' + date + '/';
    return time + "_" + number;
}


export function videoSelect(e: any) {
    let files = e.target.files;
    let videoFiles = [];
    for (let i = 0; i < files.length; i++) {
        const name = removeSuffix(files[i].name, '.mp4')
        videoFiles[i] = {
            title: name,
            status: "等待上传",
            file: files[i]
        };
    }
    return videoFiles;
}


export function uploadWithSDK(num:number = 0, file:any) {
    return new Promise((resolve, reject) => {
        var config = { useCdnDomain: true };
        var putExtra: any = {
            customVars: {}
        };
        // eslint-disable-next-line
        var finishedAttr: any = [];
        // eslint-disable-next-line
        var compareChunks: any = [];
        var observable;
        var key = file.file.name;
        var temp = key.split('.');
        var fileName2 = getTimeId(8, 12)
        var pathname = "video/" + createPic() + fileName2;//七牛云的路径  如果在目录路径是：根目录/pageck/test 那么这个值就是：page/test
        key = pathname + '.' + temp[temp.length - 1];//详细的文件名称（包含路径）page/test/test.zip  就会自动上传到相对应的文件夹

        var board: any = {};
        putExtra.customVars["x:name"] = key.split(".")[0];
        board.start = true;
        file.status = "进度：准备上传中";
        var str = Date.now()
        var error = function (err: any) {
            board.start = true;
            // $(".control-upload").text("继续上传");
            reject({
                ...file,
                num: num,
                progress:  file.status,
                cMessage: '上传出错',
                file: file,
                response: err,
               
            })
            alert("上传出错")
        };
        var complete = function (res: any) {
            console.log(res);
            file.video_path = res.key
            resolve({
                ...file,
                video_path: res.key,
                num: num,
                cMessage: '上传成功',
                file: file,
                response: res
            })
        };

        var next = function (response: any) {
            var chunks = response.chunks || [];
            var total = response.total;//上传总进度 因为如果文件过大 接口会自动分段上传
            // 这里对每个chunk更新进度，并记录已经更新好的避免重复更新，同时对未开始更新的跳过
            for (var i = 0; i < chunks.length; i++) {
                if (chunks[i].percent === 0 || finishedAttr[i]) {
                    continue;
                }
                if (compareChunks[i].percent === chunks[i].percent) {
                    continue;
                }
                if (chunks[i].percent === 100) {
                    finishedAttr[i] = true;
                }
            }
            file.status = "进度：" + parseInt(total.percent) + "%";
            compareChunks = chunks;
        };

        var subObject = {
            next: next,
            error: error,
            complete: complete
        };
        var subscription;
        // 调用sdk上传接口获得相应的observable，控制上传和暂停
        board.start = false;
        // 重要的调用接口
        observable = qiniu.upload(file.file, key, qiniuToken, putExtra, config);
        // 上传的接口 暂停的接口为observable.unsubscribe(subObject);
        subscription = observable.subscribe(subObject);
    })
}

class Qiniu {
    constructor () {
       this.getQiniuToken()
    }
    getQiniuToken() {
        getQiniuToken({}).then(res => {
            qiniuToken = res.token;
        })
    }
    async upload(videoFiles: any) {
        if (!videoFiles) {
            return Promise.reject({
                cMessage: '请选择需要上传的文件',
            })
        }
        if (!qiniuToken) {
            await this.getQiniuToken()
        }
        if (!Array.isArray(videoFiles)) {
            return new Promise((resolve, reject) => {
                uploadWithSDK(0, videoFiles).then((res) => {
                    resolve({
                        code: '',
                        res: res
                    })
                }).catch((err) => {
                    reject(err)
                });
            })
        }
        const promiseList = []
        for (var i = 0; i < videoFiles.length; i++) {
            promiseList[i] = uploadWithSDK(i, videoFiles[i])
        }
        return Promise.all(promiseList).then(res => {
            return Promise.resolve(res)
        }).catch((res) => {
            return Promise.reject({
                cMessage: '指上传错误',
                response: res
            })
        })
    }

}

export default new Qiniu()

